package com.situ.mall.admin.controller;

import com.ramostear.captcha.HappyCaptcha;
import com.ramostear.captcha.support.CaptchaType;
import com.situ.mall.admin.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/")
public class LoginController {
    @Autowired
    private IUserService userService;

    @GetMapping("/login")
    public String page() {
        return "login";
    }

    @PostMapping("/login")
    public String login(String username, String password, String captcha, HttpServletRequest request, Model model) {

        //Verification Captcha
        boolean flag = HappyCaptcha.verification(request,captcha,true);
        if(flag){
            //Other operations...
            boolean b = userService.check(username, password);
            if (b) {
//            重定向到主页
                return "redirect:/";
            } else {
                model.addAttribute("errMsg","用户名或密码错误");
                return "login";
            }
        }else {
            model.addAttribute("errMsg","验证码输入错误");
            return "login";

        }


    }


    @GetMapping("/captcha")
    public void happyCaptcha(HttpServletRequest request, HttpServletResponse response) {
        HappyCaptcha.require(request, response).type(CaptchaType.ARITHMETIC).build().finish();
    }

}
